package com.eight.travel.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eight.travel.dao.UserMapper;
import com.eight.travel.pojo.User;
import com.eight.travel.service.UserService;
import com.eight.travel.utils.BaseResp;
import com.eight.travel.utils.JWTUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Q小旭
 * @version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${source}")
    private String source;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    @ApiOperation(value = "发送邮件",notes = "将验证码发送到指定的邮箱")
    public BaseResp sendMail(String mail, HttpServletRequest request) throws MessagingException {
        //定义邮件发送功能
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //设置含有html格式的文本对象
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(mail);
        mimeMessageHelper.setSubject("验证码");
        String checkcode = getCode(5);
        //        将验证码存进context中
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("checkcode",checkcode);
        mimeMessageHelper.setText("点<a href='http://localhost:8081/register#/login'>这里</a>返回,验证码:" + checkcode, true);
        javaMailSender.send(mimeMessage);
        return new BaseResp().SUCCESS("邮件发送成功", null, null);
    }

    @Override
    @ApiOperation(value = "用户登录",notes = "用户输入信息，验证并加密")
    public BaseResp login(User user,ServletContext servletContext) {
        User user1 = userMapper.selectOne(user.getUsername(),user.getPassword());
        if (user1 == null){
            return new BaseResp().FAIL("没有账号,请注册！");
        }
        //邮箱验证码的判断
        Object o = servletContext.getAttribute("checkcode");
        if (o != null && o instanceof String){
            String checkcode = (String) o;
            if (!user.getCheckcode().equals(checkcode)){
                return new BaseResp().FAIL("邮箱验证失败");
            }
        }
        //生成token,jwt生成header,payload,sign
        Map map = new HashMap<>();
        map.put("id",user.getUid());
        map.put("name",user.getUsername());
        String jwt = JWTUtils.createJWT(map);
        return new BaseResp().SUCCESS("登录成功!",jwt,null);
    }

    @Override
    @ApiOperation(value = "用户注册",notes = "用户输入信息，验证之后返回")
    public BaseResp register(User user) {
        User one = userMapper.selectOne(user.getUsername(), user.getPassword());
        if (one != null){
            return new BaseResp().FAIL("已有账号，请登录");
        }
        int i= userMapper.add(user);
        if (i > 0){
            return new BaseResp().SUCCESS("注册成功",null,null);
        }
        return null;
    }

    @Override
    public BaseResp findAll(Integer page, Integer size) {
        //声明分页条件
        Page<User> of = Page.of(page,size);
        Page<User> userPage = userMapper.selectPage(of, null);
        return new BaseResp().SUCCESS("查询成功",userPage,(int)userPage.getTotal());
    }

    @Override
    public BaseResp deleteById(User user) {
        int i = userMapper.deleteById(user.getUid());
        if (i > 0 ){
            return new BaseResp().SUCCESS("删除成功",null,null);
        }
        return new BaseResp().FAIL("删除失败");
    }

    @ApiOperation(value = "验证码",notes = "通过随机数生成验证码")
    public  String getCode(int len) {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 1; i <= len; i++) {
            //用随机数，随机取出一个数字下标
            int j = random.nextInt(source.length());
            stringBuffer.append(source.substring(j, j + 1));
        }
        return stringBuffer.toString();
    }



}